module repository.DeviceTokenRepository;

import hunt.entity;
import hunt.logging;
import std.conv : to;
import std.array;
import bootstrap.DatabaseBootstrap;
import model;
import message.MsgDefine;
import core.stdc.time;
import std.uuid;
import hunt.framework;
class DeviceTokenRepository: EntityRepository!( DeviceToken , int)
{
  this()
  {
    super( defaultEntityManager());
  }

  DeviceToken[] findToken(uint userId)
  {
    return findAll(new Condition("%s = %s" , Field.userId , userId));
  }

  DeviceToken findByToken(string token)
  {
    return find(new Condition("%s = '%s'" , Field.token , token));
  }



  void putToken(string token, uint userId)
  {
      //auto tokens = findToken(userId);
      //bool has = false;
      //foreach(DeviceToken t; tokens)
      //{
      //    if(t.token == token)
      //    {
      //        has = true;
      //        break;
      //    }
      //}
      scope(exit)
      {
        _manager.close();
      }
      auto dtoken =  findByToken(token);
      if (dtoken !is null )
      {
          if(dtoken.userId != userId)
          {
            remove(dtoken);

            auto insert = _manager.createQuery!(DeviceToken)("INSERT INTO DeviceToken u(u.token,u.userId) values (:token,:userId)");
            insert.setParameter("token",token);
            insert.setParameter("userId",userId);
            insert.exec();
          }
      }
      else
      {
        auto insert = _manager.createQuery!(DeviceToken)("INSERT INTO DeviceToken u(u.token,u.userId) values (:token,:userId)");
        insert.setParameter("token",token);
        insert.setParameter("userId",userId);
        insert.exec();
      }

  }
}
